package com.scale;

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.client.*;
import com.mongodb.client.internal.MongoClientImpl;
import org.bson.Document;

public class MongoDbUtils {
    private static MongoDatabase database;
    static {
        // 创建 MongoDB 连接
       // MongoClient mongo = new MongoClientImpl("localhost", 27017);
        //mongodb+srv://<username>:<password>@<hostname>:<port>/<auth db>?connectTimeoutMS=2000
        MongoClient mongo =  MongoClients.create(
                MongoClientSettings.builder()
                        .applyConnectionString(new ConnectionString("mongodb://localhost:27017"))
                        .build());

        // 连接到 MongoDB
//        MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
//        System.out.println("Credentials ::" + credential);

        // 访问数据库
        database = mongo.getDatabase("u-test");
        System.out.println("Connect to database successfully!");
        System.out.println("MongoDatabase info is : " + database.getName());
        // 检索集合
        MongoCollection<Document> collection = database.getCollection("scale");
        System.out.println("chose collection : " + collection.getNamespace());

        // 获取 iterable 对象
        FindIterable<Document> iterDoc = collection.find();

        // 获取迭代器
        for (Document document : iterDoc) {
            System.out.println(document);
        }
    }

    public static void main(String[] args) {

    }
}
